import { DownOutlined, PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Dropdown, Menu, Tooltip, Tabs, Card, Switch } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import React, { useState, useRef } from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import DataForm from './components/DataForm';
import { TableListItem } from './data.d';
import router from "umi/router";
import { queryRule, updateRule, addRule, removeRule } from './service';
import Styles from './index.less';
import { selectEnum } from '@/utils/utils';
import * as RequestHelper from '@/helpers/RequestHelper';
import PreviewForm from '@/components/PreviewForm';
import { FormValueType } from '@/pages/crm/depart/components/UpdateForm';
import * as TsxHelper from '@/helpers/TsxHelper';
interface TableListProps extends FormComponentProps { }
const { TabPane } = Tabs;

const TableList: React.FC<TableListProps> = props => {
    // 初始化变量区
    // 维护API状态数据
    const [apiState, setApiState] = useState<any>({ common: {} });
    const [type, setType] = useState<any>(3);
    const [nameList, setnameList] = useState<any>([]);
    // 是否更新 关键变量
    const [isUpdate, setIsUpdate] = useState<boolean>(false);
    // 表单可见 关键变量
    const [dataModalVisible, handleDataModalVisible] = useState<boolean>(false);
    // 图片预览
    const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
    const [previewImg, setPreviewImg] = useState('');
    const [content, setcontent] = useState('该扩展配置将呈现在发布流程的「编辑器」中，例如「投票」扩展可以让「编辑器」支持为帖子附带投票功能。');
    // 表单数据
    const [dataFormValues, setDataFormValues] = useState({});
    // 选中的记录
    const [rowKeys, setRowKeys] = useState<string[] | number[]>([]);

    const actionRef = useRef<ActionType>();

    const handleName = (val) => {
        setnameList(val)
    }
    const getTabKey = () => {
        const url = '/operation/expandManagement';
        const tabKey = location.pathname.replace(`${url}/`, '');
        if (tabKey && tabKey !== '/') {
            return tabKey;
        }
        return '3';
    };
    const handleTabChange = (key: string) => {
        const url = '/operation/expandManagement';
        switch (key) {
            case '3':
                setcontent('该扩展配置将呈现在发布流程的「编辑器」中，例如「投票」扩展可以让「编辑器」支持为帖子附带投票功能。')
                router.push(`${url}/3`);
                break;
            case '4':
                setcontent('该扩展配置将呈现在「帖子」列表页面中，包括全局、关注、附近、小组、搜索等结果的帖子列表，用于输出指定「类型」的帖子。')
                router.push(`${url}/4`);
                break
            case '5':
                setcontent('该该扩展配置将呈现在帖子、评论、用户主页的「更多」功能列表中，例如「投诉」扩展可以让用户在「更多」功能里对相应目标进行投诉。')
                router.push(`${url}/5`);
                break;
            case '6':
                setcontent('该扩展配置将呈现在「小组」主页中，例如「纯链接扩展插件」可以在「小组」主页显示一个超链接。')
                router.push(`${url}/6`);
                break;
            case '7':
                setcontent('该扩展配置将呈现在「用户中心」的“我的”页面中，例如「钱包」扩展可以让用户中心多一个钱包入口，点击后进入对应的插件功能。')
                router.push(`${url}/7`);
                break;
            case '8':
                setcontent('该扩展配置将呈现在「用户资料」管理功能列表中，例如「修改用户名插件」可以让修改资料功能支持修改用户名。')
                router.push(`${url}/8`);
                break;
            default:
                break;
        }
    };
    const tabList = [
        {
            key: '3',
            tab: '编辑器扩展',
        },
        {
            key: '4',
            tab: '内容类型扩展',
        },
        {
            key: '5',
            tab: '管理扩展',
        },
        {
            key: '6',
            tab: '小组扩展',
        },
        {
            key: '7',
            tab: '用户功能扩展',
        },
        {
            key: '8',
            tab: '用户资料扩展',
        },
    ];
    // 列定义
    const columns: ProColumns<TableListItem>[] = [
        {
            title: formatMessage({ id: 'app.base.display_order' }),
            dataIndex: 'rank_num',
        },
        {
            title: formatMessage({ id: 'app.base.associated_plug-in' }),
            dataIndex: 'plug_name',
        },
        {
            title: formatMessage({ id: 'app.base.display_name' }),
            dataIndex: 'name',
            hideInSearch: true,
        },
        {
            title: formatMessage({ id: 'app.base.application_scenarios' }),
            dataIndex: 'sceneNames',
            hideInSearch: true,
        },
        {
            title: (
                <>
                    {formatMessage({ id: 'app.base.number_of_applications' })}
                    <Tooltip placement="top" title={apiState?.common?.editerNumberTips}>
                        <QuestionCircleOutlined style={{ marginLeft: 4 }} />
                    </Tooltip>
                </>
            ),
            dataIndex: 'editor_number',
            hideInSearch: true,
        },
        {
            title: (
                <>
                    {formatMessage({ id: 'app.base.user_roles_authorized_to_use' })}
                    <Tooltip placement="top" title={apiState?.common?.roleUsersTips}>
                        <QuestionCircleOutlined style={{ marginLeft: 4 }} />
                    </Tooltip>
                </>
            ),
            dataIndex: 'roleNames',
            hideInSearch: true,
        },
        {
            title: formatMessage({ id: 'app.base.custom_parameters' }),
            dataIndex: 'parameter',
            hideInSearch: true,
        },
        {
            title: formatMessage({ id: 'app.base.enabled_state' }),
            dataIndex: '',
            render: (_, record) => (
                <Switch checked={record.is_enable} onChange={async () => {
                    let s = await handleUpdateItem({ id: record.id, is_enable: (!record.is_enable).toString() });
                    s && actionRef.current?.reload();
                }} />
            )
        },
        {
            title: formatMessage({ id: 'app.base.option' }),
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                    <a
                        onClick={() => {
                            handleDataModalVisible(true);
                            setDataFormValues(record);
                            setIsUpdate(true);
                            handleName(record.nameArr)
                        }}
                    >
                        {formatMessage({ id: 'app.base.set_up' })}
                    </a>
                </>
            ),
        },
    ];


    const tabList1 = (<>
        <p className={Styles.title}>该扩展配置将呈现在发布流程的「编辑器」中，例如「投票」扩展可以让「编辑器」支持为帖子附带投票功能。</p>
        <ProTable<TableListItem>
            headerTitle=""
            actionRef={actionRef}
            rowKey="key"
            search={false}
            toolBarRender={(action, { selectedRows }) => [
                selectedRows && selectedRows.length > 0 && (
                    <Dropdown
                        overlay={
                            <Menu
                                onClick={async e => {
                                    if (e.key === 'remove') {
                                        TsxHelper.showDeleteConfirm(
                                            'danger',
                                            handleRemove,
                                            selectedRows,
                                            () => {
                                                setRowKeys([]);
                                                action.reload();
                                            }
                                        )
                                    }
                                }}
                                selectedKeys={[]}
                            >
                                <Menu.Item key="remove">
                                    {formatMessage({ id: 'app.base.batch_delete' })}
                                </Menu.Item>
                            </Menu>
                        }
                    >
                        <Button>
                            {formatMessage({ id: 'app.base.batch_option' })} <DownOutlined />
                        </Button>
                    </Dropdown>
                ),
                // @ts-ignore
                <Button icon={<PlusOutlined />} type="primary" onClick={() => {
                    setIsUpdate(false);
                    let name = [];
                    apiState?.common?.multilingualoption?.map(item => {
                        let obj = {
                            key: item.key,
                            text: item.text,
                            lang_content: ''
                        }
                        name.push(obj)
                    })
                    console.log(name, 32)
                    setnameList(name);
                    handleDataModalVisible(true);
                }}>
                    {formatMessage({ id: 'app.base.create' })}
                </Button>,
            ]}

            request={params => getTableData(params)}
            columns={columns}
            rowSelection={{
                onChange: (selectedRowKeys, selectedRows) => {
                    setRowKeys(selectedRowKeys);
                },
                selectedRowKeys: rowKeys,
            }}
        /></>);
    // 请求接口数据, 设置组件状态
    const getTableData = (params: any) => {
        params.type = type;
        return queryRule(params).then((res: any) => {
            setApiState(res.data)
            return res.data.listData
        })
    }
    const callback = (key) => {
        console.log(key);
        setType(key)
        //getTableData({type:key})
    }
    const { children } = props;
    // 表单提交
    const handleSubmitDataForm = (value: any) => {
        return new Promise((resolve, reject) => {
            let s = isUpdate ? handleUpdate(value) : handleAdd(value);
            resolve(s);
        }).then(status => {
            console.log("handleSubmitDataForm status is ", status)
            if (status) {
                handleDataModalVisible(false)
                setIsUpdate(false)
                setDataFormValues({})
                if (actionRef.current) {
                    actionRef.current.reload();
                }
            }
            // 返回执行结果:boolean, 子组件接收此值来重置数据
            return status;
        })
    }


    return (
        <PageHeaderWrapper
            tabList={tabList}
            content={content}
            tabActiveKey={getTabKey()}
            onTabChange={handleTabChange}>
                {children}
            {/* <Card>
                <Tabs onChange={callback}>
                    <TabPane tab="编辑器扩展" key="3">

                    </TabPane>
                    <TabPane tab="搜索类型扩展" key="4">
                        <p className={Styles.title}>该扩展配置将呈现在「帖子」列表页面中，包括全局、关注、小组、搜索等结果的帖子列表，用于筛选帖子「类型」。</p>
                        <ProTable<TableListItem>
                            headerTitle=""
                            actionRef={actionRef}
                            rowKey="key"
                            search={false}
                            toolBarRender={(action, { selectedRows }) => [
                                selectedRows && selectedRows.length > 0 && (
                                    <Dropdown
                                        overlay={
                                            <Menu
                                                onClick={async e => {
                                                    if (e.key === 'remove') {
                                                        TsxHelper.showDeleteConfirm(
                                                            'danger',
                                                            handleRemove,
                                                            selectedRows,
                                                            () => {
                                                                setRowKeys([]);
                                                                action.reload();
                                                            }
                                                        )
                                                    }
                                                }}
                                                selectedKeys={[]}
                                            >
                                                <Menu.Item key="remove">
                                                    {formatMessage({ id: 'app.base.batch_delete' })}
                                                </Menu.Item>
                                            </Menu>
                                        }
                                    >
                                        <Button>
                                            {formatMessage({ id: 'app.base.batch_option' })} <DownOutlined />
                                        </Button>
                                    </Dropdown>
                                ),
                                // @ts-ignore
                                <Button icon={<PlusOutlined />} type="primary" onClick={() => { setIsUpdate(false); setnameList([]); handleDataModalVisible(true); }}>
                                    {formatMessage({ id: 'app.base.create' })}
                                </Button>,
                            ]}

                            request={params => getTableData(params)}
                            columns={columns2}
                            rowSelection={{
                                onChange: (selectedRowKeys, selectedRows) => {
                                    setRowKeys(selectedRowKeys);
                                },
                                selectedRowKeys: rowKeys,
                            }}
                        />
                    </TabPane>
                    <TabPane tab="管理扩展" key="5">
                        <p className={Styles.title}>该扩展配置将呈现在帖子、评论、用户主页的「更多」功能列表中，例如「投诉」扩展可以让用户在「更多」功能里对相应目标进行投诉。</p>
                        <ProTable<TableListItem>
                            headerTitle=""
                            actionRef={actionRef}
                            rowKey="key"
                            search={false}
                            toolBarRender={(action, { selectedRows }) => [
                                selectedRows && selectedRows.length > 0 && (
                                    <Dropdown
                                        overlay={
                                            <Menu
                                                onClick={async e => {
                                                    if (e.key === 'remove') {
                                                        TsxHelper.showDeleteConfirm(
                                                            'danger',
                                                            handleRemove,
                                                            selectedRows,
                                                            () => {
                                                                setRowKeys([]);
                                                                action.reload();
                                                            }
                                                        )
                                                    }
                                                }}
                                                selectedKeys={[]}
                                            >
                                                <Menu.Item key="remove">
                                                    {formatMessage({ id: 'app.base.batch_delete' })}
                                                </Menu.Item>
                                            </Menu>
                                        }
                                    >
                                        <Button>
                                            {formatMessage({ id: 'app.base.batch_option' })} <DownOutlined />
                                        </Button>
                                    </Dropdown>
                                ),
                                // @ts-ignore
                                <Button icon={<PlusOutlined />} type="primary" onClick={() => { setIsUpdate(false); setnameList([]); handleDataModalVisible(true); }}>
                                    {formatMessage({ id: 'app.base.create' })}
                                </Button>,
                            ]}

                            request={params => getTableData(params)}
                            columns={columns3}
                            rowSelection={{
                                onChange: (selectedRowKeys, selectedRows) => {
                                    setRowKeys(selectedRowKeys);
                                },
                                selectedRowKeys: rowKeys,
                            }}
                        />
                    </TabPane>
                    <TabPane tab="小组扩展" key="6">
                        <p className={Styles.title}>该扩展配置将呈现在「小组」主页中，例如「纯链接扩展插件」可以在「小组」主页显示一个超链接。</p>
                        <ProTable<TableListItem>
                            headerTitle=""
                            actionRef={actionRef}
                            rowKey="key"
                            toolBarRender={(action, { selectedRows }) => [
                                selectedRows && selectedRows.length > 0 && (
                                    <Dropdown
                                        overlay={
                                            <Menu
                                                onClick={async e => {
                                                    if (e.key === 'remove') {
                                                        TsxHelper.showDeleteConfirm(
                                                            'danger',
                                                            handleRemove,
                                                            selectedRows,
                                                            () => {
                                                                setRowKeys([]);
                                                                action.reload();
                                                            }
                                                        )
                                                    }
                                                }}
                                                selectedKeys={[]}
                                            >
                                                <Menu.Item key="remove">
                                                    {formatMessage({ id: 'app.base.batch_delete' })}
                                                </Menu.Item>
                                            </Menu>
                                        }
                                    >
                                        <Button>
                                            {formatMessage({ id: 'app.base.batch_option' })} <DownOutlined />
                                        </Button>
                                    </Dropdown>
                                ),
                                // @ts-ignore
                                <Button icon={<PlusOutlined />} type="primary" onClick={() => { setIsUpdate(false); setnameList([]); handleDataModalVisible(true); }}>
                                    {formatMessage({ id: 'app.base.create' })}
                                </Button>,
                            ]}

                            request={params => getTableData(params)}
                            columns={columns4}
                            rowSelection={{
                                onChange: (selectedRowKeys, selectedRows) => {
                                    setRowKeys(selectedRowKeys);
                                },
                                selectedRowKeys: rowKeys,
                            }}
                        />
                    </TabPane>
                    <TabPane tab="用户功能扩展" key="7">
                        <p className={Styles.title}>该扩展配置将呈现在「用户中心」的“我的”页面中，例如「钱包」扩展可以让用户中心多一个钱包入口，点击后进入对应的插件功能。</p>
                        <ProTable<TableListItem>
                            headerTitle=""
                            actionRef={actionRef}
                            rowKey="key"
                            search={false}
                            toolBarRender={(action, { selectedRows }) => [
                                selectedRows && selectedRows.length > 0 && (
                                    <Dropdown
                                        overlay={
                                            <Menu
                                                onClick={async e => {
                                                    if (e.key === 'remove') {
                                                        TsxHelper.showDeleteConfirm(
                                                            'danger',
                                                            handleRemove,
                                                            selectedRows,
                                                            () => {
                                                                setRowKeys([]);
                                                                action.reload();
                                                            }
                                                        )
                                                    }
                                                }}
                                                selectedKeys={[]}
                                            >
                                                <Menu.Item key="remove">
                                                    {formatMessage({ id: 'app.base.batch_delete' })}
                                                </Menu.Item>
                                            </Menu>
                                        }
                                    >
                                        <Button>
                                            {formatMessage({ id: 'app.base.batch_option' })} <DownOutlined />
                                        </Button>
                                    </Dropdown>
                                ),
                                // @ts-ignore
                                <Button icon={<PlusOutlined />} type="primary" onClick={() => { setIsUpdate(false); setnameList([]); handleDataModalVisible(true); }}>
                                    {formatMessage({ id: 'app.base.create' })}
                                </Button>,
                            ]}

                            request={params => getTableData(params)}
                            columns={columns5}
                            rowSelection={{
                                onChange: (selectedRowKeys, selectedRows) => {
                                    setRowKeys(selectedRowKeys);
                                },
                                selectedRowKeys: rowKeys,
                            }}
                        />
                    </TabPane>
                    <TabPane tab="用户资料扩展" key="8">
                        <p className={Styles.title}>该扩展配置将呈现在「用户资料」管理功能列表中，例如「修改用户名插件」可以让修改资料功能支持修改用户名。</p>
                        <ProTable<TableListItem>
                            headerTitle=""
                            actionRef={actionRef}
                            rowKey="key"
                            search={false}
                            toolBarRender={(action, { selectedRows }) => [
                                selectedRows && selectedRows.length > 0 && (
                                    <Dropdown
                                        overlay={
                                            <Menu
                                                onClick={async e => {
                                                    if (e.key === 'remove') {
                                                        TsxHelper.showDeleteConfirm(
                                                            'danger',
                                                            handleRemove,
                                                            selectedRows,
                                                            () => {
                                                                setRowKeys([]);
                                                                action.reload();
                                                            }
                                                        )
                                                    }
                                                }}
                                                selectedKeys={[]}
                                            >
                                                <Menu.Item key="remove">
                                                    {formatMessage({ id: 'app.base.batch_delete' })}
                                                </Menu.Item>
                                            </Menu>
                                        }
                                    >
                                        <Button>
                                            {formatMessage({ id: 'app.base.batch_option' })} <DownOutlined />
                                        </Button>
                                    </Dropdown>
                                ),
                                // @ts-ignore
                                <Button icon={<PlusOutlined />} type="primary" onClick={() => { setIsUpdate(false); setnameList(apiState.common.multilingualoption); handleDataModalVisible(true); }}>
                                    {formatMessage({ id: 'app.base.create' })}
                                </Button>,
                            ]}

                            request={params => getTableData(params)}
                            columns={columns5}
                            rowSelection={{
                                onChange: (selectedRowKeys, selectedRows) => {
                                    setRowKeys(selectedRowKeys);
                                },
                                selectedRowKeys: rowKeys,
                            }}
                        />
                    </TabPane>
                </Tabs>
            </Card> */}

            <DataForm
                dataModalVisible={dataModalVisible}
                isUpdate={isUpdate}
                dataFormValues={dataFormValues}
                common={apiState.common || {}}
                selectType={type}
                handleName={handleName}
                nameList={nameList}
                onSubmit={async formValue => handleSubmitDataForm(formValue)}
                onCancel={() => handleDataModalVisible(false)}
            />
            {
                previewModelVisible && (
                    <PreviewForm
                        previewModelVisible={previewModelVisible}
                        onVisibleModel={handlePreviewModalVisible}
                        previewImg={previewImg}
                    />
                )
            }
        </PageHeaderWrapper>
    );
};

/**
* 添加节点
* @param fields
*/
const handleAdd = async (fields: any) => {
    return RequestHelper.bdExec({
        fn: addRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.store-success' }),
        failMsg: formatMessage({ id: 'app.base.api-exception' }),
    });
};

/**
* 更新节点
* @param fields
*/
const handleUpdate = async (fields: FormValueType) => {
    return RequestHelper.bdExec({
        fn: updateRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.update-success' }),
        failMsg: formatMessage({ id: 'app.base.api-exception' }),
    });
};

// @ts-ignore
/**
 *  删除节点
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
    if (!selectedRows) return true;
    const ids: any = selectedRows.map(row => row.id).toString();
    return RequestHelper.bdExec({
        fn: removeRule,
        args: { ids },
        successMsg: formatMessage({ id: 'app.base.destroy-success' }),
        failMsg: formatMessage({ id: 'app.base.api-exception' }),
        hasLoading: false
    });
};

const handleUpdateItem = async (fields: FormValueType) => {
    return RequestHelper.bdExec({ fn: updateRule, args: fields, successMsg: '更新成功', failMsg: '更新失败请重试！' });
};
export default Form.create<TableListProps>()(TableList);
